package org.example.services.impl;

import org.example.model.UserDO;
import org.example.model.dto.UserDetailDTO;
import org.example.services.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

/**
 * 用户名密码
 */
@Service("domainUserDetailService")
public class DomainUserDetailService implements UserDetailsService {

    private static final Logger logger = LoggerFactory.getLogger(DomainUserDetailService.class);

    @Autowired
    private UserService userService;

    @Override
    public UserDetailDTO loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDO oneByUsername = userService.getOneByUsername(username);
        if(oneByUsername==null){
            logger.error("找不到用户：{}",username);
            throw new UsernameNotFoundException("用户" + username + "不存在!");
        }

        // TODO 加载用户的权限
        Set<GrantedAuthority> authorities=new HashSet<>();
        authorities.add(new SimpleGrantedAuthority("chen_"));
//        authorities.add(new SimpleGrantedAuthority("admin"));
        UserDetailDTO userDetailDTO = new UserDetailDTO(oneByUsername.getUserId(),
                oneByUsername.getUsername(),
                oneByUsername.getPassword(),
                oneByUsername.getHeadImage(),
                oneByUsername.getSuperMan(),
                authorities);
        return userDetailDTO;
    }
}
